﻿using System;
using TraditionalMalteseCuisine.App_Code.Functions;
using TraditionalMalteseCuisine.App_Code.Objects;

namespace TraditionalMalteseCuisine
{
    public partial class Register : System.Web.UI.Page
    {
        #region Page Load
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        #endregion


        #region Buttons
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (dtpDOB.IsValid())
            {
                SiteMember member = new SiteMember();

                member.Username = txtUsername.Text;
                member.Password = txtPassword.Text;
                member.EMail = txtEMail.Text;
                member.FirstName = txtFirstName.Text;
                member.LastName = txtLastName.Text;
                member.DOB = dtpDOB.SelectedDate;
                member.Gender = cmbGender.SelectedValue;

                csvImageLocation.IsValid = ((uplImageLocation.FileName.Length == 0) || (Validation_Functions.IsValidImageFile(uplImageLocation.FileName)));
                csvUsernameExists.IsValid = (!Site_Functions.DoesUsernameExists(member.Username));
                csvEMailExists.IsValid = (!Site_Functions.DoesEmailExists(member.EMail));

                if (uplImageLocation.FileName.Length > 0)
                {
                    string newImageFileName = string.Format("{0}{1}", Guid.NewGuid().ToString(), uplImageLocation.FileName.Substring(uplImageLocation.FileName.LastIndexOf('.')));
                    member.ImageLocation = string.Format("{0}{1}", SiteMember.DEFAULT_IMAGE_FOLDER_LOCATION, newImageFileName);
                    member.ThumbnailLocation = string.Format("{0}{1}", SiteMember.DEFAULT_THUMBNAIL_FOLDER_LOCATION, newImageFileName);
                }

                if ((csvImageLocation.IsValid) && (csvUsernameExists.IsValid) && (csvEMailExists.IsValid) && (Site_Functions.AddSiteMember(member)))
                {
                    if (uplImageLocation.FileName.Length > 0)
                    {
                        Site_Functions.SaveImageFile(uplImageLocation, Request.MapPath(member.ImageLocation), Request.MapPath(member.ThumbnailLocation), 32);
                    }

                    Site_Functions.SendRegistrationConfirmationEMail(member);

                    lblMessage.Visible = true;

                    Response.AddHeader("REFRESH", string.Format("5;URL=signin.aspx?continueon=profile.aspx?user={0}", Site_Functions.GetSiteMemberDetailsUsingEMail(member.EMail).ID));
                }
            }
        }
        #endregion
    }
}